#pragma once

#include <poll.h>
#include <sys/types.h>
#include <unistd.h>
#include <sys/time.h>
#include "Log.hpp"
#include "Socket.hpp"

#define FD_NONE -1

class PollServer
{
public:
    PollServer(const uint16_t &port = 8080)
        : _port(port)
    {
        _listensock = Sock::Socket();
        Sock::Bind(_listensock, _port);
        Sock::Listen(_listensock);

        _rfds = new struct pollfd[_nrfds];
        for(int i = 0; i < _nrfds; ++i)
        {
            _rfds[i].fd = FD_NONE;
            _rfds[i].events = _rfds[i].revents = 0;
        }
        _rfds[0].fd = _listensock;
        _rfds[0].events = POLLIN;
    }

    void start()
    {
        // listensock本质就是IO，在linsten的时候就完成了TCP三次握手，并且放在了全连接的队列里面
        // accept本质是从listensock文件里读，看看是否有就绪 -- 阻塞式
        // 这里想要用select，交给他等
        while (true)
        {
            int ret = poll(_rfds, _nrfds, _timeout);
            switch (ret)
            {
            case 0:
                Messagelog(DEBUG, "time out ...");
                break;
            case -1:
                Messagelog(WARNING, "poll error %d:%s", errno, strerror(errno));
                break;
            default:
                // 就绪了，处理
                HandlerEvent();
                break;
            }
        }

        // 测试
        // int fd = Sock::Accept(_listensock, nullptr, nullptr);
        // std::cout << fd << std::endl;
    }

    ~PollServer()
    {
        if (_listensock > 0)
            close(_listensock);
        if(_rfds) delete[] _rfds;
    }

private:
    void HandlerEvent()
    {
        // rfds是就绪的名单
        for(int pos = 0; pos < _nrfds; ++pos)
        {
            if(_rfds[pos].fd == FD_NONE) continue;
            if(!(_rfds[pos].revents & POLLIN)) continue;
            // 就绪的pos
            if(pos == 0) Accepter();
            else Recver(pos);
        }
    }

    // listen
    void Accepter()
    {
        int sock = Sock::Accept(_listensock, nullptr, nullptr);
        if(sock < 0) exit(1);
        int i = 0;
        for(; i < _nrfds; ++i)
        {
            if(_rfds[i].fd == FD_NONE) break;
        }
        if(i == _nrfds) {
            Messagelog(ERROR, "_rfds full close sock %d", sock);
            close(sock);
        }
        else {
            _rfds[i].fd = sock;
            _rfds[i].events = POLLIN;
            Messagelog(DEBUG, "accept successful sock %d", sock);
        }
    }

    void Recver(int pos)
    {
        char buffer[1024];
        ssize_t sz = recv(_rfds[pos].fd, buffer, sizeof(buffer) - 1, 0);
        if(sz > 0)
        {
            buffer[sz] = 0;
            std::cout << "client[ " << _rfds[pos].fd << " ]: " << buffer << std::endl;
        }
        else if(sz == 0)
        {
            Messagelog(DEBUG, "client[%d] quit, me too...",_rfds[pos].fd);
            close(_rfds[pos].fd);
            _rfds[pos].fd = FD_NONE;
            _rfds[pos].events = POLLIN;
        }
        else
        {
            Messagelog(ERROR, "Recv sock[%d] error %d:%s", _rfds[pos].fd, errno, strerror(errno));
        }
    }

private:
    uint16_t _port;
    int _listensock;
    size_t _nrfds = 100;
    struct pollfd* _rfds;
    int _timeout = 1000;
};